/* eslint-disable array-callback-return */
import React from 'react';
import { connect } from 'dva';
import { MinusCircleOutlined, PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Input, Row, Col, message, Spin, Modal } from 'antd';
import router from 'umi/router';
import FooterToolbar from '@/components/FooterToolbar';

const FormItem = Form.Item;
const { confirm } = Modal;

@connect(({ supplier, loading }) => ({
  supplier,
  loading: loading.models.supplier,
}))
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      custId: null,
      listIndex: 0,
    };
  }

  componentDidMount = () => {
    const { custId } = this.props;
    this.setState({ custId });
    this.getList();
  };

  // 获取数据
  getList = () => {
    const { custId, dispatch } = this.props;
    dispatch({
      type: 'supplier/getCostCenter',
      payload: { custId },
    });
  };

  // 新增数据
  add = () => {
    const {
      dispatch,
      supplier: { costCenterList },
    } = this.props;
    const { listIndex, custId } = this.state;
    const newData = costCenterList.map(item => ({ ...item }));
    newData.push({
      costCenterId: `list_${listIndex}`,
      custId,
      name: '',
    });
    this.state.listIndex += 1;
    dispatch({
      type: 'supplier/updateModalData',
      payload: { costCenterList: newData },
    });
  };

  // 删除数据
  delList = costCenterId => {
    const {
      supplier: { costCenterList },
      dispatch,
    } = this.props;
    const newData = costCenterList.filter(item => item.costCenterId !== costCenterId);
    confirm({
      title: '你确定要刪除此条成本中心信息吗？',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk() {
        if (costCenterId.indexOf('list_') > -1) {
          // 新增
          message.success('删除成功！');
        } else {
          dispatch({
            type: 'supplier/delCostCenter',
            payload: { costCenterId },
          });
        }
        dispatch({
          type: 'supplier/updateModalData',
          payload: { costCenterList: newData },
        });
      },
    });
  };

  // 新增修改提交数据
  submitData = () => {
    const {
      supplier: { costCenterList },
      dispatch,
      form,
    } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        costCenterList.map(item => {
          const temp = item;
          Object.keys(values).forEach(key => {
            if (key.indexOf('list_') > -1 && key === item.costCenterId) {
              temp.costCenterId = '';
              temp.name = values[key];
            }
            if (key === item.costCenterId) {
              temp.name = values[key];
            }
          });
        });
        dispatch({
          type: 'supplier/costcenterInsert',
          payload: { costCenterList },
        });
      }
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const {
      supplier: { costCenterList },
      loading,
    } = this.props;
    const xl = { span: 8 };
    const lg = { span: 8 };
    const md = { span: 8 };
    const sm = 24;
    const colProps = { xl, lg, md, sm };
    return (
      <Spin spinning={loading}>
        <Row style={{ marginBottom: '20px' }}>
          <Button type="primary" onClick={this.add}>
            <PlusOutlined />
            新增
          </Button>
        </Row>
        <Form layout="vertical">
          <Row gutter={64}>
            {costCenterList.map((item, index) => (
              <Col {...colProps} key={item.costCenterId ? item.costCenterId : index}>
                <FormItem>
                  {getFieldDecorator(item.costCenterId ? item.costCenterId : `list_${index}`, {
                    rules: [{ required: true, message: '请输入' }],
                    initialValue: item.name ? item.name : '',
                  })(<Input placeholder="请输入" style={{ width: '90%' }} />)}
                  <MinusCircleOutlined
                    className="dynamic-delete-button"
                    onClick={() => this.delList(item.costCenterId)}
                  />
                </FormItem>
              </Col>
            ))}
          </Row>
        </Form>
        <FooterToolbar style={{ width: '100%' }}>
          <Button
            onClick={() => router.push('/salemanage/customerinfo/list')}
            style={{ marginRight: 10 }}
          >
            取消
          </Button>
          <Button type="primary" onClick={this.submitData}>
            提交
          </Button>
        </FooterToolbar>
      </Spin>
    );
  }
}

const BasicFormList = Form.create()(BasicForm);
export default BasicFormList;
